import React, { memo, useState } from "react";
import { login, register } from "../api/todo";
import { useNavigate } from "react-router-dom";
import { Form, Input ,Button,Toast} from "antd-mobile";
const Login = memo(() => {
  const navigate = useNavigate();
  const onFinish =async (values) => {
      let res =  await login(values)
      if(res.data.success){
        Toast.show({
          icon: 'success',
          content: '登录成功',
        })
        localStorage.setItem("token",res.data.data.token)
        navigate('/home')
      }
  }
  const onFinish1 =async (values) => {
      let res =  await register(values)
      if(res.data.success){
        Toast.show({
          icon: 'success',
          content: '注册成功',
        })
        registerForm.resetFields()
      }
  }
  const [registerForm] = Form.useForm()
  return (
    <div>
      {/* 登录功能 */}
      <Form onFinish={onFinish} name="loginForm">
        <Form.Item
          name="username"
          label="账号"
          rules={[{ required: true, message: "账号不能为空" }]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input  placeholder="请输入密码" type="password"/>
        </Form.Item>
        <Button block type='submit' color='primary' size='large'>
            登录
          </Button>
      </Form>
      <hr />
      {/* 注册功能 */}
      <Form onFinish={onFinish1} name="registerForm" form={registerForm}>
        <Form.Item
          name="username"
          label="账号"
          rules={[{ required: true, message: "账号不能为空" }]}
        >
          <Input placeholder="请输入账号" />
        </Form.Item>
        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: "密码不能为空" }]}
        >
          <Input  placeholder="请输入密码" type="password"/>
        </Form.Item>
        <Button block type='submit' color='primary' size='large'>
            注册
          </Button>
      </Form>
    </div>
  );
});

export default Login;
